package com.leyantech.ecp.agenx.common.misc;

import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.util.GlobalTracer;
import io.vertx.core.Handler;
import io.vertx.tracing.opentracing.OpenTracingUtil;

import java.util.function.Supplier;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-28.
 */
public class TracingHelper {

  public static <T> Handler<T> tracingHandler(Handler<T> delegate) {
    return tracingHandler(delegate, OpenTracingUtil::getSpan);
  }

  public static <T> Handler<T> tracingHandler(Handler<T> delegate, Supplier<Span> spanSupplier) {
    return event -> {
      final Span span = spanSupplier.get();
      try (Scope ignore = span == null ? null : GlobalTracer.get().scopeManager().activate(span)) {
        delegate.handle(event);
      }
    };
  }

}
